package pl.kosmowska.ewelina.server;

import gwtupload.server.exceptions.UploadActionException;
import gwtupload.server.gae.AppEngineUploadAction;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import javax.servlet.http.HttpServletRequest;

import net.sf.flatpack.DataSet;
import net.sf.flatpack.DefaultParserFactory;
import net.sf.flatpack.Parser;

import org.apache.commons.fileupload.FileItem;

 
public class FileUploadServlet extends  AppEngineUploadAction {
 
	private static final long serialVersionUID = 1L;
	@Override 
	public String executeAction(HttpServletRequest request,
			List<FileItem> sessionFiles) throws UploadActionException {

		StringBuilder responseBuilder = new StringBuilder();
		for (FileItem item : sessionFiles) {
			if (!item.isFormField()) {
				try {
					//String content = item.getContentType();
					InputStream inputStream = item.getInputStream();
					String file = convertStreamToString(inputStream);
					int beg = file.indexOf("#Data operacji");
					int end = file.indexOf(";;;;;;");
					file = file.substring(beg,end);
					String alteredFile=removeSemiColonsAtTheEnd(file);

					//Obtain the proper parser for your needs
			    	Parser parser = DefaultParserFactory.getInstance().newDelimitedParser(
			    			new StringReader(alteredFile),  //txt file to parse
			                ';', //delimiter
			                '"'); //text qualifier

			        //obtain DataSet
			        DataSet ds = parser.parse();
			        
			        
			        while (ds.next()){ //loop through file
			        	responseBuilder.append(ds.getString("#Data operacji"));
			        	responseBuilder.append("|");
			        	responseBuilder.append(ds.getString("#Tytu\u0142"));
			        	responseBuilder.append("|");
			        	responseBuilder.append(replaceCommaWithDot(removeSpaceBar(ds.getString("#Kwota"))));
			        	responseBuilder.append("#");
			        }
			        responseBuilder.deleteCharAt(responseBuilder.length()-1);
			      
 
				} catch (Exception e) {
					throw new UploadActionException(e.getMessage());
				}
			}
		}
 
		try {
			// Remove files from session
			//removeSessionFileItems(request);
		} catch (Exception e) {
			throw new UploadActionException(e.getMessage());
		}
 
		// Send information of the received files to the client.
		return responseBuilder.toString();
	}
	
	   public String convertStreamToString(InputStream is)
	            throws IOException {
	        /*
	        * To convert the InputStream to String we use the
	        * Reader.read(char[] buffer) method. We iterate until the
	        * Reader return -1 which means there's no more data to
	        * read. We use the StringWriter class to produce the string.
	        */
	        if (is != null) {
	            Writer writer = new StringWriter();

	            char[] buffer = new char[1024];
	            try {
	                Reader reader = new BufferedReader(
	                        new InputStreamReader(is, "Cp1250"));
	                int n;
	                while ((n = reader.read(buffer)) != -1) {
	                    writer.write(buffer, 0, n);
	                }
	            } finally {
	                is.close();
	            }
	            return writer.toString();
	        } else {
	            return "";
	        }
	    }



		private  String removeSemiColonsAtTheEnd(String file) {
			Scanner scanner = new Scanner(file);
			List<String>lines = new ArrayList<String>();
			while (scanner.hasNextLine()) {
			  String line = scanner.nextLine();
			  if(line.length()>0){
				  line = line.substring(0, line.length()- 1);
				  lines.add(line);
			  }
			  // process the line
			}
			String alteredFile="";
			for(String line: lines){
				alteredFile+=line+"\n";
			}
			return alteredFile;
		}
		
	    public static String removeSpaceBar(String input){
	        return input.replace(" ","");
	    }
	    
	    public static String replaceCommaWithDot(String input){
	        return input.replace(",",".");
	    }
	    

 
}